import themeChangeBehavior from 'tdesign-miniprogram/mixins/theme-change';
const { login, fetchUserInfo, checkLoginStatus } = require('../../utils/api.js');
const { checkCryptoLibs } = require('../../utils/crypto-utils.js');

Page({
  behaviors: [themeChangeBehavior],
  
  data: {
    // 表单数据
    formData: {
      employeeNumber: '',
      name: '',
      password: '',
      type: ''
    },
    // UI状态
    selectedRole: '',
    isLogging: false,
    showPassword: false,
    canLogin: false,
    // 角色列表
    roles: [
      { value: 1, label: '组员', icon: 'user', color: '#00A870' },
      { value: 2, label: '组长', icon: 'user', color: '#0052D9' },
      { value: 3, label: '仓库管理员', icon: 'shop', color: '#E37318' }
    ],
    // 加密状态
    encryptionReady: false,
    encryptionMessage: '检查加密功能...'
  },

  onLoad() {
    // 检查是否已登录
    if (checkLoginStatus()) {
      this.redirectToWorkbench();
      return;
    }
    
    // 检查加密功能
    this.checkEncryptionStatus();
  },

  /**
   * 检查加密功能状态
   */
  checkEncryptionStatus() {
    try {
      const libCheck = checkCryptoLibs();
      
      if (libCheck.ready) {
        this.setData({
          encryptionReady: true,
          encryptionMessage: '加密功能就绪'
        });
      } else {
        this.setData({
          encryptionReady: false,
          encryptionMessage: '加密库未就绪'
        });
        
        wx.showModal({
          title: '加密功能异常',
          content: '登录需要加密库支持，请确保已正确配置crypto-js和wxmp-rsa。\n\n解决方案：\n1. 在微信开发工具中点击"工具"->"构建npm"\n2. 重新编译项目',
          showCancel: false,
          confirmText: '我知道了'
        });
      }
      
      this.checkCanLogin();
    } catch (error) {
      this.setData({
        encryptionReady: false,
        encryptionMessage: '检查失败'
      });
    }
  },

  // 表单输入处理
  onEmployeeNumberInput(e) {
    this.setData({
      'formData.employeeNumber': e.detail.value
    });
    this.checkCanLogin();
  },

  onNameInput(e) {
    this.setData({
      'formData.name': e.detail.value
    });
    this.checkCanLogin();
  },

  onPasswordInput(e) {
    this.setData({
      'formData.password': e.detail.value
    });
    this.checkCanLogin();
  },

  // 切换密码显示
  togglePassword() {
    this.setData({
      showPassword: !this.data.showPassword
    });
  },

  // 检查是否可以登录
  checkCanLogin() {
    const { employeeNumber, name, password } = this.data.formData;
    const canLogin = employeeNumber.trim() && 
                    name.trim() && 
                    password.trim() && 
                    this.data.selectedRole &&
                    this.data.encryptionReady;
    this.setData({ canLogin });
  },

  onRoleSelect(e) {
    const role = e.currentTarget.dataset.role;
    this.setData({
      selectedRole: role
    });
    this.checkCanLogin();
  },

  /**
   * 登录处理
   */
  async onLogin() {
    // 验证表单
    if (!this.validateForm()) {
      return;
    }

    // 检查加密功能
    if (!this.data.encryptionReady) {
      wx.showModal({
        title: '无法登录',
        content: '加密功能未就绪，无法安全登录。请重新检查加密配置。',
        showCancel: false
      });
      return;
    }

    // 防止重复点击
    if (this.data.isLogging) {
      return;
    }

    this.setData({ isLogging: true });

    try {
      wx.showLoading({
        title: '登录中...',
        mask: true
      });

      // 构建登录数据
      const loginData = {
        username: this.data.formData.name.trim(),
        phone: '',
        account: this.data.formData.employeeNumber.trim(),
        password: this.data.formData.password.trim(),
        type: this.data.selectedRole
      };
      
      // 执行加密登录
      const result = await login(loginData);

      wx.hideLoading();

      if (result.success) {
        wx.showToast({
          title: '登录成功',
          icon: 'success',
          duration: 1500
        });

        // 获取完整用户信息
        await fetchUserInfo();

        // 检查是否为首次登录
        const isFirstLogin = result.data && result.data.firstLogin;
        
        if (isFirstLogin) {
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/change-password/change-password?firstLogin=true&canSkip=false'
            });
          }, 1500);
        } else {
          setTimeout(() => {
            this.redirectToWorkbench();
          }, 1000);
        }
      } else {
        wx.showToast({
          title: result.message || '登录失败',
          icon: 'none',
          duration: 3000
        });
      }
    } catch (error) {
      wx.hideLoading();
      wx.showToast({
        title: error.message || '登录失败，请检查网络连接',
        icon: 'none',
        duration: 3000
      });
    } finally {
      this.setData({ isLogging: false });
    }
  },

  // 验证登录表单
  validateForm() {
    const { employeeNumber, name, password } = this.data.formData;
    
    if (!employeeNumber.trim()) {
      wx.showToast({
        title: '请输入工号',
        icon: 'none'
      });
      return false;
    }

    if (!name.trim()) {
      wx.showToast({
        title: '请输入姓名',
        icon: 'none'
      });
      return false;
    }

    if (!password.trim()) {
      wx.showToast({
        title: '请输入密码',
        icon: 'none'
      });
      return false;
    }

    if (!this.data.selectedRole) {
      wx.showToast({
        title: '请选择类型',
        icon: 'none'
      });
      return false;
    }

    return true;
  },

  /**
   * 重新检查加密功能
   */
  onRetryEncryption() {
    this.checkEncryptionStatus();
  },

  onUnload() {
    wx.hideLoading();
  },

  /**
   * 跳转到工作中心
   */
  redirectToWorkbench() {
    wx.switchTab({
      url: '/pages/workbench/workbench',
      fail: (err) => {
        wx.reLaunch({
          url: '/pages/workbench/workbench',
          fail: (relaunchErr) => {
            wx.showModal({
              title: '跳转失败',
              content: '页面跳转失败，请手动切换到工作中心页面',
              showCancel: false
            });
          }
        });
      }
    });
  }
});